<?php

namespace App\Api\Service\Trigonal;

use Illuminate\Support\Facades\Http;

class WxminiQrcodeService
{
    public function __construct()
    {
        $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $this->appid = $sys_setting_repositories->get(16);
        $this->secret = $sys_setting_repositories->get(17);
    }

    public function get_qrcode($uid, $type = 1)
    {
        $access_token = $this->get_access_token();
        $page = $type == 1 ? 'pages/searchResult/detail/index' : 'pages/index/index';
        $this->get_unlimited($uid, $page, $access_token, $type);
    }

    private function get_access_token()
    { //TODO
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
        $user_obj = json_decode(Http::get($url), true);
        return $user_obj['access_token'];
    }

    private function get_unlimited($scene, $page, $access_token, $type)
    {
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $data = [
            'scene' => "i" . $scene,
            'page' => $page,
            'width' => 600,
            'auto_color' => false,
        ];
        //拿到二维码
        $path = $type == 1 ? "uploads/qrcode/" . $scene . ".png" : "uploads/qrcode/" . $scene . "_index.png";
        file_put_contents($path, Http::post($url, $data));
        return true;
    }

    private function data_uri($contents, $mime)
    {
        $base64 = base64_encode($contents);
        return ('data:' . $mime . ';base64,' . $base64);
    }
}
